#region Using

using System;
using System.Xml;
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.Specialized;
using BlogEngine.Core;
using BlogEngine.Core.Providers;
using BlogEngine.Core.Provider.Interfaces;

#endregion

namespace BlogEngine.Core.Provider.XML
{
	/// <summary>
	/// A storage provider for BlogEngine that uses XML files.
	/// <remarks>
	/// To build another provider, you can just copy and modify
	/// this one. Then add it to the web.config's BlogEngine section.
	/// </remarks>
	/// </summary>
	public class CISettings : ISettings
	{
		private static string _fileName = Provider.Folder + "settings.xml";

		/// <summary>
		/// Loads the settings from the provider.
		/// </summary>
		public StringDictionary Load()
		{
			StringDictionary dic = new StringDictionary();

			XmlDocument doc = new XmlDocument();
			doc.Load(_fileName);

			foreach (XmlNode settingsNode in doc.SelectSingleNode("settings").ChildNodes)
			{
				string name = settingsNode.Name;
				string value = settingsNode.InnerText;

				dic.Add(name, value);
			}

			return dic;
		}

		/// <summary>
		/// Saves the settings to the provider.
		/// </summary>
		public void Save(StringDictionary settings)
		{
			if (settings == null)
				throw new ArgumentNullException("settings");

			XmlWriterSettings writerSettings = new XmlWriterSettings(); ;
			writerSettings.Indent = true;

			//------------------------------------------------------------
			//    Create XML writer against file path
			//------------------------------------------------------------
			using (XmlWriter writer = XmlWriter.Create(_fileName, writerSettings))
			{
				writer.WriteStartElement("settings");

				foreach (string key in settings.Keys)
				{
					writer.WriteElementString(key, settings[key]);
				}

				writer.WriteEndElement();
			}
		}

	}
}
